package com.jinlejia.bbs.http.utils;

import android.content.Context;
import android.text.TextUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.jinlejia.bbs.http.entity.base.PageEntity;
import com.jinlejia.bbs.widget.BBSToast;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.builder.GetBuilder;
import com.zhy.http.okhttp.callback.FileCallBack;
import com.zhy.http.okhttp.request.RequestCall;

import java.io.File;
import java.util.List;
import java.util.Map;

import okhttp3.Call;
import okhttp3.MediaType;
import okhttp3.Request;

/**
 * @author 王进 on 2019/3/22.
 */

public final class HttpUtils {
    public static RequestCall httpCall(String url) {
        return httpCall(url, null);
    }

    public static RequestCall httpCall(String url, JSONObject json) {
        GetBuilder builder = OkHttpUtils.get()
                .url(url);
        if (json != null) {
            for (String key : json.keySet()) {
                builder.addParams(key, String.valueOf(json.get(key)));
            }
        }
        return builder.build();
    }

    /**
     * 创建一个请求对象
     * @param url  请求的HTTP 全路径
     * @param json 要传递的表单数据
     */
    public static RequestCall httpCallForm(String url, JSONObject json) {
        return OkHttpUtils.postString()
                .url(url)
                .mediaType(MediaType.parse("application/json; charset=utf-8"))
                .content(json.toString())
                .build();
    }


    public static RequestCall httpCallFile(String url,File file){
        return OkHttpUtils.postFile()
                .url(url)
                .file(file)
                .build();
    }



    public static FileCallBack httpFileCallBack(final Context context,File dir,String fileName){
        return new FileCallBack(dir.getPath(),fileName) {
            @Override
            public void onError(Call call, Exception e, int id) {

            }

            @Override
            public void onResponse(File response, int id) {

            }
        };
    }

    /**
     * 生成一个返回地址
     */
    public static MapCallBack httpCallBack(final Context context, final HttpCallBack callBack) {
        return new MapCallBack() {

            @Override
            public void onBefore(Request request, int id) {
                super.onBefore(request, id);
            }

            @Override
            public void onAfter(int id) {
                super.onAfter(id);
            }

            @Override
            public void onError(Call call, Exception e, int id) {
                if (callBack != null) {
                    callBack.onError(e);
                }
            }

            @Override
            public void onResponse(Map<String, Object> response, int id) {
                if (callBack==null)return;
                if (DataFilter.filter(context, response)) {
                    String data = String.valueOf(response.get("data"));
                    JsonParse parse = new JsonParse(data);
                    callBack.onResponse(parse);
                }else {
                    int code = 0;
                    if (response.containsKey("code")){
                        try{
                            code = Integer.parseInt(response.get("code").toString());
                        }catch (Exception ignored){
                        }
                    }
                    if (code==204){ //没有数据
                        String data = String.valueOf(response.get("data"));
                        JsonParse parse = new JsonParse(data);
                        callBack.onResponse(parse);
                    }else {
                        callBack.onNoResponse(code);
                        if (!callBack.onProxyMessage(response)){
                            if (response.get("message") != null){
                                BBSToast.showToast(context,String.valueOf(response.get("message")),1500);
                            }
                        }
                    }
                }
            }
        };
    }


    public final static class JsonParse{
        private String data;
        private JsonParse(String data){
            this.data = data;
        }

        /**
         * <pre>
         * 传递的值可以使用以下代码进行创建，其中的T为你要使用的数据源
         * TypeReference&lt;PageEntity&lt;T&gt;&gt; reference = new TypeReference&lt;PageEntity&lt;T&gt;&gt;() {};
         * </pre>
         */
        public <T extends PageEntity> PageEntity<T> parsePageEntity(TypeReference<PageEntity<T>> reference){
            String tempData = data;
            if ("null".equalsIgnoreCase(tempData) || TextUtils.isEmpty(tempData)){
                tempData = "{\"nextPageAvailable\": false,\"totalItem\": 0,\"data\": []}";
            }
            return JSON.parseObject(tempData, reference);
        }

        public <T> List<T> parseArray(Class<T> clazz){
            String tempData = data;
            if ("null".equalsIgnoreCase(tempData) || TextUtils.isEmpty(tempData)){
                tempData = "[]";
            }
            return JSON.parseArray(tempData, clazz);
        }

        public <T> T parse(Class<T> tClass){
            String tempData = data;
            if ("null".equalsIgnoreCase(tempData) || TextUtils.isEmpty(tempData)){
                tempData = "";
            }
            return JSON.parseObject(tempData,tClass);
        }

        public JSONObject data(){
            String tempData = data;
            if ("null".equalsIgnoreCase(tempData) || TextUtils.isEmpty(tempData)){
                tempData = "";
            }
            return JSON.parseObject(tempData);
        }
    }

}
